import React, {useEffect, useState} from 'react';
import {Routes, Route, Navigate, Outlet} from 'react-router-dom';
import Login from '@/view/login';
import Home from '@/view/Home';
import NotFound from '@/view/NotFound';
import AppLayout from '@/components/layout'; // 引入你的 Layout 组件
const RouteConfig = () => {
    // 创建 isAuth 状态
    const [isAuth, setIsAuth] = useState(!!window.localStorage.getItem("token"));

    // 监听 localStorage 的变化
    useEffect(() => {
        const handleStorageChange = () => {
            setIsAuth(!!window.localStorage.getItem("token"));
        };

        window.addEventListener("storage", handleStorageChange);

        return () => {
            window.removeEventListener("storage", handleStorageChange);
        };
    }, []);

    return (
        <Routes>
            {/* 登录页面 */}
            <Route path="/login" element={isAuth ? <Navigate to="/index"/> : <Login onLogin={() => setIsAuth(true)}/>}/>

            {/* Layout 作为父组件包裹子路由 */}
            <Route path="/" element={isAuth ? <AppLayout><Outlet/></AppLayout> : <Navigate to="/login"/>}>
                <Route path="index" element={<Home/>}/>
                <Route path="*" element={<NotFound/>}/>
            </Route>

            {/* 默认重定向到登录页面 */}
            <Route path="/" element={<Navigate to="/login"/>}/>
        </Routes>
    );
};

export default RouteConfig;
